﻿ import Taro, { Component } from '@tarojs/taro'
import { Swiper, SwiperItem, Image, View, Text,Input} from '@tarojs/components'
import '../../assets/common.scss'
import CommonJs from '../../utils/common'
import './mybill.scss'
import ewmtb from '../../assets/kedouimg01/ewmtb.png'


export default class Index extends Component {             
  constructor(props) {   
    super(props);                                    
    this.state = {         
      userinfo:Taro.getStorageSync('userinfo'), 
      qid:Taro.getStorageSync('dateinfo').qid,                                                 
      myBuyinputc:'', 
      bl:'',
      dealerId:'',
      shopId:'',
      payAmount:'',
      discount:'',  
      clock:0,
      inputmount:0,
      selectmount:0,
      goodslist:[],
      sureindex:[],
      flindex:0,
      iszy:0,
      appmark:CommonJs.getmark()
    }             
  }  
  config = { 
    navigationBarTitleText: '加载中'
  }
  componentWillMount () {
  	var ciszy=Taro.getStorageSync('guide');
    this.setState({
      iszy:ciszy
    })
  	this.getShop()
  } 
  getShop(){
  	if(this.state.qid&&!this.$router.params.scene){
	    var _this = this
	    var dates = {
	      clusterId: _this.state.qid
	    }
	    CommonJs.ajaxRequest('/clusterShop/getClusterShopByclusterId',dates,'GET',function(res){
	    	 _this.setState({
		        shopId: res.content.shopId,
		        dealerId: res.content.dealerId
		      },function(){
		        _this.getbl(res.content.dealerId)
		        _this.showgoods(res.content.shopId)
		      })
	    
	      	Taro.setStorage({key:'dealerId',data:res.content.dealerId})
			Taro.setStorage({key:'shopId',data:res.content.shopId})
	    })
	}
  	else{
  		var par =this.$router.params
		if(par){
			var cs=par.scene;
			if(cs&&cs.indexOf('mybill')>=0){
				var arr=cs.split("mybill")
				var dealerId=arr[0]
				var shopinfo=arr[1]
				var carr=shopinfo.split("&")
				var shopId=carr[0]
				Taro.setStorage({key:'dealerId',data:dealerId})
				Taro.setStorage({key:'shopId',data:shopId})
			}
		}
		else{
	  		var dealerId=Taro.getStorageSync('dealerId');
	  		var shopId=Taro.getStorageSync('shopId')
	    }
  		this.setState({
			shopId:shopId,
		    dealerId:dealerId
		})
  		this.getbl(dealerId)
		this.showgoods(shopId)
  	}
  } 
  
  
  getbl(dealerId){
  	//获取积分比例
  	var _this=this;
  	var date={
  		dealerId:dealerId
  	}
  	CommonJs.ajaxRequest('/store/getDealerSupplier',date,'GET',function(res){
       // console.log(JSON.stringify(res)+'666')
       //_this.state.content = res;     
  		Taro.setNavigationBarTitle({title:"我要买单"})
  		_this.setState({
  			myBuyinputc:res.consumptionRewardCredit+"%",
  			bl:res.consumptionRewardCredit
  		})
  	})
  } 
  //输入框价格（买单）
  getpayAmount(event){
  	var m=parseFloat(event.target.value);
  	if(m){
  		m=parseFloat(m);
  	}
  	else{
  		m=0;
  	}
  	var s=parseFloat(this.state.selectmount);
    this.setState({
      payAmount:m+s,
      inputmount:m
    })
  }
  //不参与金额
  getdiscount(even){
  	this.setState({
  		discount:even.target.value	  		
  	})  	
  }
  //判断是否有cur
  getcur(){  	
  	if(this.state.clock==1){
  		//console.log(this.state.clock+"//1a")
  		this.setState({
  			clock:0
  		})
  	}else{  	
  		this.setState({
  			clock:1
  		})
  	}
  }
  //提交
  makeBill(){
  	let _this = this
    let discount = 0
    let dealerId=_this.state.dealerId 
    let shopId=_this.state.shopId
  	let payAmount=parseFloat(_this.state.payAmount)
  	let discounts=_this.state.discount
    if (discounts == '') {
      discount = 0
    } else {
      discount = parseFloat(discounts)
    }
  	if (payAmount>=0) {  
  		if(discount > payAmount){
  			Taro.showToast({
		        title:'不参与优惠金额不能大于等于消费总额！',
		        icon: 'none',
		        duration: 1500
		    })    
  		}
  		else{
  			_this.getPayMonery(dealerId,shopId,payAmount,discount)
  		}
      
  	}
    else {
      Taro.showToast({
        title:'请输入买单总金额',
        icon: 'none',
        duration: 1500
      })
    }
  }
  closezy(){
  	if(this.state.iszy>0){
  		CommonJs.ajaxRequest('/guide/updateGuide','','GET',function(res){})
  		this.guide(0);
  	}
  }
  getPayMonery(dealerId,shopId,payAmount,discountAmount){
  	var _this=this
  	let bl=_this.state.bl
  	var date={
  		shopId:shopId,
  		needPayAmount:payAmount,
  		notDiscountAmount:discountAmount  		
  	}  	
  	this.closezy();
  	CommonJs.ajaxRequest('/consume/getMaxDiscountPayOffByConsumeAmount',date,'GET',function(res){
    	//console.log(JSON.stringify(res)+'777')    	
    	if(res){
    		if(res.code!=300){
    			var goodsIds=[];
			  	var amounts=[];
			  	var goodslist=_this.state.goodslist;
			  	var pindex=_this.state.sureindex;
			  	if(pindex.length>0){
			  		
				  	for(var i=0;i<pindex.length;i++){
				  		var a=pindex[i];
				  		var b=a.split("|");
				  		var b0=b[0];
			  			var b1=b[1];
				  		goodsIds.push(goodslist[b0].commodityCoupons[b1].goodsId);
				  		amounts.push(goodslist[b0].commodityCoupons[b1].amount);
				  	}
    				_this.$preload({
				  		id:res.id,
				  		discount:res.discount,			  		
				  		shopId:shopId,
				  		payAmount:payAmount,
				  		discountAmount:discountAmount,
				  		bl:bl,
				  		goodsIds:goodsIds,
				  		amounts:amounts
				  	})
    			}
    			else{
	    			_this.$preload({
				  		id:res.id,
				  		discount:res.discount,			  		
				  		shopId:shopId,
				  		payAmount:payAmount,
				  		discountAmount:discountAmount,
				  		bl:bl
				  	})
    			}
    			CommonJs.open('/pages/mybill/mybuy')
    		}    		
    	}
  	})  	
  }
  opendetails(url){
    CommonJs.openTo(url);
  }
   open(url){
		CommonJs.openTo(url)
	}
  
   showgoods(shopid){
  	var url="/commodityCoupon/getCommodityCouponByQuery";
  	var dates={
  		shopId:shopid
  	}
  	var _this=this;
  	CommonJs.ajaxRequest(url,dates,'GET',function(res){
  		var red=res.content;
  		/*for(var i=0;i<red.length;i++){
  			 red[i].max=red[i].amount;
  		}*/
      _this.setState({
	        goodslist:red
	    })
   })
  }
  choose(index){
  	var pindex=this.state.sureindex;
  	var flindex=this.state.flindex;
  	var goodslist=this.state.goodslist;
  	
  	var xb=pindex.indexOf(flindex+'|'+index);
  	if(xb>=0){
  		pindex.splice(xb,1);
  	}
  	else{
  		pindex.push(flindex+'|'+index);
  	}
  	this.setState({
        sureindex:pindex
    })
  	this.getpay();
  }
  choosefl(index){
  	this.setState({
    	flindex:index
    })
  }
  donum(index,type){
  	var goodslist=this.state.goodslist;
  	var pindex=this.state.sureindex;
  	var flindex=this.state.flindex;
  	if(type==1){//加
  		if(goodslist[flindex].commodityCoupons[index].amount<goodslist[flindex].commodityCoupons[index].max){
  			goodslist[flindex].commodityCoupons[index].amount=goodslist[flindex].commodityCoupons[index].amount+1;
  			
  			this.setState({
		        goodslist:goodslist
		    })
  			this.getpay();
  		}
  		else{
  			Taro.showToast({
	          title:"该奖品可兑换数量为"+goodslist[flindex].commodityCoupons[index].max,
	          icon: 'none',
	          duration: 2000
	        })
  		}
  	}
  	else{
  		if(goodslist[flindex].commodityCoupons[index].amount>1){
  			goodslist[flindex].commodityCoupons[index].amount=goodslist[flindex].commodityCoupons[index].amount-1;
  			this.setState({
		        goodslist:goodslist
		    })
  			this.getpay();
  		}
  	}
  }
  getpay(){
  	var pindex=this.state.sureindex;
  	var goodslist=this.state.goodslist;
  	var total=0;
  	var p=this.state.inputmount;
  	if(pindex.length>0){
  		for(var i=0;i<pindex.length;i++){
  			var a=pindex[i];
  			var b=a.split("|");
  			var b0=b[0];
  			var b1=b[1];
  			total=total+goodslist[b0].commodityCoupons[b1].extraprice*goodslist[b0].commodityCoupons[b1].amount;
  		}
  	}
  	this.setState({
  	  selectmount:total.toFixed(2),
      payAmount:parseFloat(p)+parseFloat(total)
   })
  }
  iscur(index){
  	var pindex=this.state.sureindex;
  	var iscur=0;
  	for(var i=0;i<pindex.length;i++){
  		var a=pindex[i];
  		var b=a.split("|");
  		if(b[0]==index){
  			iscur=1;
  		}
  	}
  	if(iscur==1){
  		return 'display:block'
  	}
  	else{
  		return 'display:none'
  	}
  }
  guide01(val){
  	let payAmount=parseFloat(this.state.payAmount)
  	if (payAmount>=0) {  
  		this.guide(val);
  	}
    else {
      Taro.showToast({
        title:'请输入买单金额',
        icon: 'none',
        duration: 1500
      })
    }
  	
  }
  guide(val){
  	this.setState({
      iszy: val
    })
  	Taro.setStorage({key:'guide',data:val})
  }
  render () {
  	const goodslist=this.state.goodslist
    return (
      <View className='page'>
      	<View className='ewm' onClick={this.open.bind(this,'/pages/my/myewm?byfrom=mybill')}>
      		<View className='ewmimg'><Image className='img' mode='widthFix' src={ewmtb}></Image></View>
      		<View className='ewmtext'>聚合支付码</View>
      	</View>
        <View className='my-bill'>
        	<View className={this.state.iszy==6?'my-buy tsrelative':'my-buy'}>
          	<Text className="my-buywz">买单金额</Text>
	      	  <Input type="digit" className="my-buyinput"   onInput={this.getpayAmount.bind(this)} placeholder="询问服务员后输入"/>		
        	</View>
        	<View className="my-buy my-buyrq fr" style="display:none;">{this.state.appmark=='xjzb'?'WUC':'积分'}赠送比例：{this.state.myBuyinputc}</View>
        	
        	<View className="my-buyone" style="display:none;">
        	   <Text className="my-buycy">不参与优惠金额</Text>        		        		
        	   <Text className={this.state.clock==0?'my-buygx':'my-buygxcur'} onClick={this.getcur.bind(this)}></Text>
        	</View>
        	
        	<View className="my-buy" style={this.state.clock==0?'display:none':'display:block'}> 
        	   <Text className="my-buywz">不参与优惠金额</Text>
	      	   <Input type="digit"  className="my-buyinput" value={this.state.discount}  onInput={this.getdiscount.bind(this)}  placeholder="询问服务员后输入"/>
        	</View>
        	
        </View>        
       
        <View className={this.state.iszy==5?'my-js tsrelative05':'my-js'}>
        	<Text className='my-btn' onClick={this.makeBill.bind(this)}>确认买单</Text>   
        	  
        	<Text className="my-js-monery">￥{this.state.payAmount}</Text>
        </View>
        
        
        
        <View className='shoplist' style={goodslist.length>0?'display:block':'display:none'}>
			<View className='shoplist-fl'>
				{goodslist.length>0&&goodslist.map((item, index) => (
					<Text className={index==this.state.flindex?'fl-li cur':'fl-li'} onClick={this.choosefl.bind(this,index)}>{item.groupName}
						<Text className='radio' style={this.iscur(index)}></Text>
					</Text>
				))}
			</View>
			<View className='shop-list shop-listts'>
					{goodslist.length>0&&goodslist[this.state.flindex].commodityCoupons.map((item, index) => (
  					<View className={this.state.iszy==4&&index==0?'goods-li tsrelative':'goods-li'}>
  						<View className={this.state.sureindex.indexOf(this.state.flindex+'|'+index)>=0?'goods-choose goods-choosecur':'goods-choose'} onClick={this.choose.bind(this,index)}></View>
  						
  						<View className="goods-logo-box"><Image className='goods-logo' mode='widthFix' src={item.commodityLogo}></Image></View>
  						<View className='goods-text'>
  							<Text className='shop-li'>{item.commodityName}</Text>
  							<Text className='shop-li shop-lits'>￥{item.extraprice}</Text>
  							<View className='goods-num'>
	  							<Text className='jia' onClick={this.donum.bind(this,index,1)}>+</Text>
	  							<Text className='val'>{item.amount}</Text>
	  							<Text className='jian' onClick={this.donum.bind(this,index,0)}>-</Text>
	  						</View>
	  						
  						</View>
  					</View>
  					
  					))}
  			</View>
		</View>
		
		<View className='bg' style={this.state.iszy>=1?'display:block':'display:none;'}></View> 
		 <View className='ydcon' style={this.state.iszy==4?'display:block;top:35%':'display:none;'}>
        	<Image className='jt' mode='widthFix' src='https://minichat.g2ma.com/kedouimg/jt.png'></Image>
        	<Text className='ydcon-text'>选择您抽中的商品进行购买</Text>
        	<View className='ydcancle' onClick={this.guide.bind(this,6)}>下一步</View>
        </View>
        <View className='ydcon' style={this.state.iszy==6?'display:block;top:10%':'display:none;'}>
        	<Image className='jt' mode='widthFix' src='https://minichat.g2ma.com/kedouimg/jt.png'></Image>
        	<Text className='ydcon-text'>输入需要买单的金额</Text>
        	<View className='ydcancle' onClick={this.guide01.bind(this,5)}>下一步</View>
        </View>
		<View className='ydcon ydcon05' style={this.state.iszy==5?'display:block;top:65%':'display:none;'}>
			<View className='ydcancle'  onClick={this.closezy}>退出新手指引</View>
        	<Text className='ydcon-text'>点击确认,后付款即可</Text>
        	<Image className='jt' mode='widthFix' src='https://minichat.g2ma.com/kedouimg/jt.png'></Image>
        </View>
      </View>
    )
  }
}

 